package study.springboot.mybatis.support.mybatis;

import com.github.pagehelper.PageInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

@Slf4j
@MapperScan(basePackages = "study.springboot.mybatis.mapper.order", sqlSessionFactoryRef = "orderSqlSessionFactory")
@Configuration
public class MybatisOrderConfig {

    @Bean("orderSqlSessionFactory")
    public SqlSessionFactoryBean orderSqlSessionFactory(@Qualifier("order_ds") DataSource ds,
                                                    @Qualifier("order_pageHelper") Properties prop) throws Exception {

        log.info("{}", prop) ;
        //
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

        //
        factoryBean.setDataSource(ds);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("study/springboot/mybatis/mapper/order/**/**.xml"));
        factoryBean.setTypeAliasesPackage("study.springboot.mybatis.mapper.order");
        factoryBean.setEnvironment("order_sql_session");
        //
        PageInterceptor interceptor = new PageInterceptor();
        interceptor.setProperties(prop);
        factoryBean.setPlugins(new Interceptor[]{interceptor});

        return factoryBean;
    }
}
